﻿using System;
using Dapper;
using Hx.Domain.Model;
using Hx.Infrastructure.Common;

namespace Hx.Domain.Repositories.Dapper
{
    public class ArticleRepository : DapperRepository<Article>, IArticleRepository
    {
        public ArticleRepository(IRepositoryContext context)
            : base(context)
        {

        }

        public PagedResult<Article> GetAllArticles(int pageIndex, int pageSize)
        {
            return DapperContext.Connection.QueryPaged<Article>(null, "CreateTime DESC", pageIndex, pageSize, "*", false, DapperContext.Transaction);
        }

        public PagedResult<Article> GetUserArticles(Guid authorId, int pageIndex, int pageSize)
        {
            return DapperContext.Connection.QueryPaged<Article>(new { AuthorId = authorId }, "CreateTime DESC", pageIndex,
                pageSize, "*", false, DapperContext.Transaction);
        }

        public PagedResult<Article> GetUserArticlesByCategoryId(Guid authorId, Guid categoryId, int pageIndex, int pageSize)
        {
            return DapperContext.Connection.QueryPaged<Article>(new { AuthorId = authorId, CategoryId = categoryId }, "CreateTime DESC", pageIndex,
                pageSize, "*", false, DapperContext.Transaction);
        }

        public PagedResult<Article> GetArticlesByCategoryId(Guid categoryId, int pageIndex, int pageSize)
        {
            return DapperContext.Connection.QueryPaged<Article>(new { CategoryId = categoryId }, "CreateTime DESC",
                pageIndex, pageSize, "*", false, DapperContext.Transaction);
        }

        public Article GetArticleById(Guid articleId)
        {
            return DapperContext.Connection.Get<Article>(new { Id = articleId }, "*", false, DapperContext.Transaction);
        }

        public bool FakeDelete(Guid id)
        {
            var dp = new DynamicParameters();
            dp.Add("Id", id);
            var result = DapperContext.Connection.Execute("UPDATE Hx_Article SET Status=0 WHERE Id=@Id", dp, DapperContext.Transaction);
            return result > 0;
        }
    }
}